//
//  KChooseImageController.m
//  Peanut
//
//  Created by Jim huang on 2018/8/27.
//  Copyright © 2018年 Jim_Peanut. All rights reserved.
//

#import "KChooseImageControlView.h"


//other
#import "TZImageManager.h"
#import "TZImagePickerController.h"

@interface KChooseImageControlView ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate,UIAlertViewDelegate>
@property (nonatomic,strong) UIViewController *baseVC;

@property (nonatomic,strong) UIImagePickerController *imagePicker;
///选择图片数量
@property (nonatomic,assign) NSInteger imageCount;
///< 允许裁剪,默认为YES，showSelectBtn为NO才生效
@property (nonatomic,assign) BOOL allowCrop;
///< 裁剪框的尺寸
@property (nonatomic,assign) CGRect cropRect;
///< 需要圆形裁剪框
@property (nonatomic,assign) BOOL needCircleCrop;
///< 圆形裁剪框半径大小
@property (nonatomic,assign) NSInteger circleCropRadius;
///确认回调
@property (nonatomic,copy) chooseImageSureBlock sureBlock;


//取消
@property (nonatomic,strong) UIButton * cancelBtn;
//拍照
@property (nonatomic,strong) UIButton * takePhotoBtn;
//相册
@property (nonatomic,strong) UIButton * photoAlbumBtn;
@end

@implementation KChooseImageControlView


#pragma mark ----other

/**
 普通构造器

 @param baseVC 父级VC
 @param imageCount 选择照片数量
 */
+ (void)showChooseImageControllerWithBaseVC:(UIViewController *)baseVC imageCount:(NSInteger)imageCount SureBlock:(chooseImageSureBlock)sureBlock{
    KChooseImageControlView * ic = [[KChooseImageControlView alloc]initWithBaseVC:baseVC imageCount:imageCount SureBlock:sureBlock];
    
    [ic show];
}


/**
 圆形裁剪构造器
 @param baseVC 父级VC
 @param circleCropRadius 裁剪框的尺寸
 */
+ (void)showCircleCropChooseImageControllerWithBaseVC:(UIViewController *)baseVC circleCropRadius:(NSInteger)circleCropRadius SureBlock:(chooseImageSureBlock)sureBlock{
    KChooseImageControlView * ic = [[KChooseImageControlView alloc]initWithBaseVC:baseVC circleCropRadius:circleCropRadius SureBlock:sureBlock];
    [ic show];
}

/**
 方形裁剪构造器
 @param baseVC 父级VC
 @param cropSize 裁剪框的尺寸
 */
+ (void)showSquareCropChooseImageControllerWithBaseVC:(UIViewController *)baseVC cropSize:(CGSize)cropSize SureBlock:(chooseImageSureBlock)sureBlock{
    KChooseImageControlView * ic = [[KChooseImageControlView alloc]initWithBaseVC:baseVC cropSize:cropSize SureBlock:sureBlock];
    [ic show];
}

/**
 普通构造器
 
 @param baseVC 父级VC
 @param imageCount 选择照片数量
 */
-(instancetype)initWithBaseVC:(UIViewController *)baseVC imageCount:(NSInteger)imageCount SureBlock:(chooseImageSureBlock)sureBlock{
    
    self = [super init];
    if (self) {
        _sureBlock = sureBlock;
        _baseVC = baseVC;
        _allowCrop = NO;
        _imageCount = imageCount;
        [self setUI];


    }
    return self;
    
}

/**
 圆形裁剪构造器
 @param baseVC 父级VC
 @param circleCropRadius 裁剪框的尺寸
 */

-(instancetype)initWithBaseVC:(UIViewController *)baseVC circleCropRadius:(NSInteger)circleCropRadius SureBlock:(chooseImageSureBlock)sureBlock{
    
    self = [super init];
    if (self) {
        _sureBlock = sureBlock;
        _baseVC = baseVC;
        _imageCount = 1;
        _allowCrop = YES;
        _needCircleCrop = YES;
        _circleCropRadius = circleCropRadius;
        [self setUI];


    }
    return self;
}

/**
 方形裁剪构造器
 @param baseVC 父级VC
 @param cropSize 裁剪框的尺寸
 */
-(instancetype)initWithBaseVC:(UIViewController *)baseVC cropSize:(CGSize)cropSize SureBlock:(chooseImageSureBlock)sureBlock{
    
    self = [super init];
    if (self) {
        _sureBlock = sureBlock;
        _baseVC = baseVC;
        _imageCount = 1;
        _allowCrop = YES;
        _cropRect = CGRectMake((kScreenWidth-cropSize.width)/2, (kScreenHeight-cropSize.height)/2, cropSize.width, cropSize.height);
        [self setUI];
    }
    return self;
}


-(void)setUI{
    
    [super setUI];
    self.contentView.layer.cornerRadius = 4.0f;
    self.contentView.clipsToBounds = YES;
    
    [self.contentView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.bottom.equalTo(self);
        make.height.equalTo(@152);
    }];
    
    
    [self.takePhotoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentView);
        make.left.right.equalTo(self.contentView);
        make.height.equalTo(@50);
    }];
    
    UIView * marginView1 = [[UIView alloc]init];
    marginView1.backgroundColor = DMGrayColor;
    [self.contentView addSubview:marginView1];
    
    [marginView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.takePhotoBtn.mas_bottom);
        make.height.equalTo(@1);
        make.left.right.equalTo(self.contentView);
    }];
    
    [self.photoAlbumBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(marginView1.mas_bottom);
        make.left.right.equalTo(self.contentView);
        make.height.equalTo(@50);
    }];
    
    UIView * marginView2 = [[UIView alloc]init];
    marginView2.backgroundColor = DMGrayColor;
    [self.contentView addSubview:marginView2];
    
    [marginView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.photoAlbumBtn.mas_bottom);
        make.height.equalTo(@1);
        make.left.right.equalTo(self.contentView);

    }];
    
    [self.cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(marginView2.mas_bottom);
        make.left.right.bottom.equalTo(self.contentView);
        
    }];
    
}


#pragma mark ----TZImagePicker----
//从相册中选取
-(void)selectPhotoToUpload{
    
    
    TZImagePickerController *imagePickerVC = [[TZImagePickerController alloc] initWithMaxImagesCount:self.imageCount delegate:nil ];
    imagePickerVC.allowPickingGif = NO;
    imagePickerVC.allowPickingVideo = NO;
    imagePickerVC.allowCrop = self.allowCrop;
    imagePickerVC.cropRect = self.cropRect;

    if (self.needCircleCrop) {
        imagePickerVC.needCircleCrop = self.needCircleCrop;
        imagePickerVC.circleCropRadius = self.circleCropRadius;
    }

    
    MJWeakSelf
    [imagePickerVC setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        if (weakSelf.sureBlock) {
            weakSelf.sureBlock(photos);
        }
        [self removeFromSuperview];

    }];
    [self.baseVC presentViewController:imagePickerVC animated:YES completion:nil];
    
}



#pragma mark - KGetImageDelegate


//获取图片信息
- (void)reloadPhotoArrayImage:(UIImage *)image {
    
    //不需要裁剪
    if (!self.allowCrop) {
        if (self.sureBlock) {
            NSArray * imageArr = [NSArray arrayWithObject:image];
            self.sureBlock(imageArr);
            return;
        }
    }
    
    //需要裁剪
    MJWeakSelf
    //获取相册最新的图片信息 也就是刚刚拍照保存的
    PHFetchOptions *options = [[PHFetchOptions alloc] init];
    PHFetchResult *assetsFetchResults = [PHAsset fetchAssetsWithOptions:options];
    PHAsset *phasset = [assetsFetchResults lastObject];
    
    
    //裁剪图片VC
    TZImagePickerController *imagePickerVC = [[TZImagePickerController alloc]initCropTypeWithAsset:phasset photo:image completion:^(UIImage *cropImage, id asset) {
        
        if (weakSelf.sureBlock) {
            NSArray * imageArr = [NSArray arrayWithObject:cropImage];
            weakSelf.sureBlock(imageArr);
        }
        [self removeFromSuperview];

    }];
    
    imagePickerVC.allowPickingGif = NO;
    imagePickerVC.allowPickingVideo = NO;
    imagePickerVC.allowCrop = self.allowCrop;
    imagePickerVC.cropRect = self.cropRect;
    if (self.needCircleCrop) {
        imagePickerVC.needCircleCrop = self.needCircleCrop;
        imagePickerVC.circleCropRadius = self.circleCropRadius;
    }
    [imagePickerVC setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        if (weakSelf.sureBlock) {
            weakSelf.sureBlock(photos);
        }
        [self removeFromSuperview];

    }];
    [self.baseVC presentViewController:imagePickerVC animated:YES completion:nil];
    
}


#pragma mark - UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

    UIImage *  image = info[UIImagePickerControllerOriginalImage];
    
    [picker dismissViewControllerAnimated:YES completion:^{
        if (![KuserInfo isCameraDeviceAvalable]) {
            [JLProgressHUDManager showErrorHud:@"需要保存到相册权限"];
            return;
        }
        
        if (image) {
            //保存图片
            [[TZImageManager manager] savePhotoWithImage:image completion:^(NSError *error){
                if (!error) {
                    [self reloadPhotoArrayImage:image];
                }
            }];
        }
    }];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self removeFromSuperview];
}

#pragma mark ----action
-(void)takePhotoAction{
    
    if (![KuserInfo isCameraDeviceAvalable]) {
        UIAlertView *alertview = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的“设置-隐私-相机”选项中，允许本应用程序访问你的相机。" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertview show];
        return;
    }
    if (!self.imagePicker) {
        self.imagePicker = [[UIImagePickerController alloc]init];
    }
    
    self.imagePicker.delegate = self;
    self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    self.imagePicker.allowsEditing = NO;
    
    self.imagePicker.showsCameraControls = YES;
    self.imagePicker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
    
    self.imagePicker.mediaTypes = @[(NSString*)kUTTypeImage];
    [self.baseVC presentViewController:self.imagePicker animated:YES completion:nil];
    [self hideView];
}



-(void)photoAlbumAction{
    if (![KuserInfo isCameraDeviceAvalable]) {
        return;
    }
    [self selectPhotoToUpload];
    [self hide];
}

- (void)hideView
{
    MJWeakSelf
    [UIView animateWithDuration:0.3 animations:^{
        
        weakSelf.contentView.alpha = 0;
        weakSelf.coverControl.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
        
    } completion:^(BOOL finished) {
        [self.coverControl removeAllSubviews];
        [self.coverControl removeFromSuperview];
        [self.contentView removeAllSubviews];
        [self.contentView removeFromSuperview];
        self.hidden = YES;
    }];
}


#pragma mark ----getting&setting
-(UIButton *)cancelBtn{
    if (!_cancelBtn) {
        _cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _cancelBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [_cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        [_cancelBtn setTitleColor:HEX_RGB(0x555555) forState:UIControlStateNormal];
        [_cancelBtn addTarget:self action:@selector(hide) forControlEvents:UIControlEventTouchUpInside];
        
        [self.contentView addSubview:_cancelBtn];
        
    }
    return _cancelBtn;
}

-(UIButton *)takePhotoBtn{
    if (!_takePhotoBtn) {
        _takePhotoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_takePhotoBtn setTitle:@"拍照" forState:UIControlStateNormal];
        _takePhotoBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [_takePhotoBtn setTitleColor:HEX_RGB(0x555555) forState:UIControlStateNormal];
        [_takePhotoBtn addTarget:self action:@selector(takePhotoAction) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:_takePhotoBtn];
    }
    return _takePhotoBtn;
}


-(UIButton *)photoAlbumBtn{
    if (!_photoAlbumBtn) {
        _photoAlbumBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_photoAlbumBtn setTitle:@"从相册选择" forState:UIControlStateNormal];
        _photoAlbumBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [_photoAlbumBtn setTitleColor:HEX_RGB(0x555555) forState:UIControlStateNormal];
        [_photoAlbumBtn addTarget:self action:@selector(photoAlbumAction) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:_photoAlbumBtn];
    }
    return _photoAlbumBtn;
}

-(void)dealloc{
    
}


@end
